#!/bin/sh
G_ML="/tmp/Adbyby/"   #安装目录
G_RZ="/tmp/Adbyby/adbyby.log"   #日志位置
G_WZ="/bin/0ad_byby_sh.sh"  #守护脚本位置
G_AZB="http://update.adbyby.com/download/7620n.tar.gz"   #程序安装包下载地址
G_BBL=10       #开机无网超时，单位:分钟。
G_IP=180.76.76.76
G_UP="update.adbyby.com"
G_BLL=0
G_JGG=5
killall -s 9 koolproxy
iptables -t nat -F KOOLPROXY
iptables -t nat -F KOOLPROXY_HTTP
iptables -t nat -F KOOLPROXY_HTTPS
iptables -t nat -F PREROUTING
mkdir "$G_ML"
while [ "$G_BLL" -eq 0 ] ;
do
sleep $G_JGG
if ping -w 1 -c 1 "$G_IP"
then
G_JGG=5
if ping -w 1 -c 1 "$G_UP"
then
G_BLL=1
G_JGG=5
else
if [ "$G_JGG" -eq 5 ];then
echo -e "\n"$(date +"%Y-%m-%d %H:%M:%S")         "【错误】无法连接Adbyby服务器！已自动监控服务器，待恢复后安装Adbyby……" >> "$G_RZ"
fi
G_BLL=0
G_JGG=599
fi
else
if [ "$G_JGG" -eq 5 ];then
echo -e "\n"$(date +"%Y-%m-%d %H:%M:%S")         "【错误】无法连接互联网！已自动监控网络，待恢复后安装Adbyby……" >> "$G_RZ"
fi
G_BLL=0
G_JGG=59
fi
done
ntpd -q -n -d -p s2g.time.edu.cn
G_BL=1
echo -e "\n"$(date +"%Y-%m-%d %H:%M:%S")         "开始安装 Adbyby …… " >> "$G_RZ"
while [ "$G_BL" -le "$G_BBL" ] ;
do
killall -s 9 adbyby
iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
rm -rf /tmp/7620n.tar.gz
wget -qO /tmp/7620n.tar.gz "$G_AZB" && tar -xzvf /tmp/7620n.tar.gz -C "$G_ML" && rm /tmp/7620n.tar.gz && mv "$G_ML"bin/* "$G_ML" && chmod 777 "$G_ML"adbyby && "$G_ML"adbyby&
sleep 10
G_ZF=`ps | grep adbyby | wc -l`
 if [ "$G_ZF" -ne 3 ];then
  echo $(date +"%Y-%m-%d %H:%M:%S")    "【警告】Adbyby 第【"$G_BL"】 次安装失败，60秒后再次安装……" >> "$G_RZ"
 let G_BL=$G_BL+1
 sleep 59
 else
 echo $(date +"%Y-%m-%d %H:%M:%S")      "Adbyby 尝试了【"$G_BL"】次，安装成功！" >> "$G_RZ"
G_BL=999999
 fi
 done
 if [ "$G_BL" -eq 999999 ];then
  iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
  iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
  iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
  sh $G_WZ&
  echo $(date +"%Y-%m-%d %H:%M:%S")        "Adbyby守护脚本启动成功！" >> "$G_RZ"
  exit 0
 else  
   echo $(date +"%Y-%m-%d %H:%M:%S")    "【致命错误】Adbyby 安装失败！！！  " >> "$G_RZ"
  exit 0
  fi
exit 0

    